package ms.maplestory.boot.client.character;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import ms.maplestory.boot.enums.JobType;
import ms.maplestory.boot.service.jobs.IJobService;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Getter
@Setter
@Component
@RequiredArgsConstructor
public class JobManager {

    private int id;

    private final ApplicationContext applicationContext;
    private static final Map<JobType, IJobService> handlers = new HashMap<>();

    public static IJobService getJobByIdAndChar(int id, Char chr) {
        JobType jobType = JobType.getJobById(id);
        if (jobType != null) {
            IJobService jobService = handlers.get(jobType);
            if (jobService != null) {
                jobService.init(chr);
                return jobService;
            }
        }
        return null;
    }

    @PostConstruct
    public void initHandlers() {
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(ms.maplestory.boot.service.jobs.Job.class);
        beans.forEach((name, value) -> {
            ms.maplestory.boot.service.jobs.Job jobAnnotation = value.getClass().getAnnotation(ms.maplestory.boot.service.jobs.Job.class);
            if (jobAnnotation != null && IJobService.class.isAssignableFrom(value.getClass())) {
                JobType[] jobEnums = jobAnnotation.value();
                if (jobEnums.length > 0) {
                    for (JobType h : jobEnums) {
                        handlers.put(h, (IJobService) value);
                    }
                }
            }
        });
    }
}
